﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BillGuru.Persistence;

namespace BillGuru
{
    public partial class FrmStockMaster : Form
    {
        private const char CodedFieldSeperator = ',';
        private const char FreeFieldSeperator = ' ';

        public FrmStockMaster()
        {
            InitializeComponent();
        }


        private void frmMaster_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'billGuruDataSet.UnitOfMeasure' table. You can move, or remove it, as needed.
            this.unitOfMeasureTableAdapter.Fill(this.billGuruDataSet.UnitOfMeasure);
            this.attributeValueTableAdapter.Fill(this.billGuruDataSet.AttributeValue);
            this.attributeTableAdapter.Fill(this.billGuruDataSet.Attribute);
            this.productTypeTableAdapter.Fill(this.billGuruDataSet.ProductType);
            

            this.productTypeTableAdapter.Adapter.RowUpdated += new System.Data.OleDb.OleDbRowUpdatedEventHandler(Adapter_GenericRowUpdated);
            this.attributeTableAdapter.Adapter.RowUpdated += new System.Data.OleDb.OleDbRowUpdatedEventHandler(Adapter_GenericRowUpdated);
            this.productTypeTableAdapter.Adapter.RowUpdated += new System.Data.OleDb.OleDbRowUpdatedEventHandler(Adapter_GenericRowUpdated);
            this.unitOfMeasureTableAdapter.Adapter.RowUpdated += new System.Data.OleDb.OleDbRowUpdatedEventHandler(Adapter_GenericRowUpdated);

        }

        void Adapter_GenericRowUpdated(object sender, System.Data.OleDb.OleDbRowUpdatedEventArgs e)
        {
            SharedEventHandlerImpl.RetrieveKeyOnRowInsert(sender, e);
        }

        private void pbSave_Click(object sender, EventArgs e)
        {
            saveAll();
        }

        public BillGuru.BillGuruDataSet.ProductDataTable NewProducts
        {
            get
            {
                return billGuruDataSet.Product;
            }
        }

        private void pbDone_Click(object sender, EventArgs e)
        {
            this.Close();
        }



        private void productTypeBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            saveAll();
        }

        private void saveAll()
        {
            if (!billGuruDataSet.HasChanges())
                return;

            DialogResult result = MessageBox.Show("All changes will be saved, Are you sure?", "Save Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
            if (result == DialogResult.No)
                return;

            this.Validate();
            this.productTypeBindingSource.EndEdit();
            this.attributeBindingSource.EndEdit();
            this.attributeValueBindingSource.EndEdit();
            this.unitOfMeasureBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.billGuruDataSet);
        }

        private void bpCreate_Click(object sender, EventArgs e)
        {
            if (productTypeDataGridView.SelectedRows.Count != 1 || unitOfMeasureDataGridView.SelectedRows.Count == 0)
            {
                MessageBox.Show("Please select a single product type row and one or more Unit of Measure", "Select Product Type & UOM ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            int productTypeID = (int)productTypeDataGridView.SelectedRows[0].Cells["ProductTypeID"].Value;

            BillGuruDataSet.AttributeRow[] attributes = (from att in billGuruDataSet.Attribute
                                                         where att.ProductTypeID == productTypeID
                                                         orderby att.Priority
                                                         select att).ToArray();

            BillGuruDataSet.AttributeValueRow[][] values = new BillGuruDataSet.AttributeValueRow[attributes.Count()][];
            int i = 0;

            foreach (BillGuruDataSet.AttributeRow attrib in attributes)
            {
                values[i++] = (from avv in billGuruDataSet.AttributeValue
                 where avv.AttributeID == attrib.ID select avv).ToArray();
            }

            List<Names> productDescriptions = new List<Names>();

            productDescriptions.Add(new Names((string)productTypeDataGridView.SelectedRows[0].Cells["Acronym"].Value, (string)productTypeDataGridView.SelectedRows[0].Cells["ProductType"].Value));
            
            createProductDescriptions(ref productDescriptions, values);

            createProducts(productDescriptions);
            
        }

        private void createProducts(List<Names> descriptions)
        {
            BillGuruDataSet.ProductTypeRow productTypeRow = (BillGuruDataSet.ProductTypeRow)billGuruDataSet.ProductType.Rows[productTypeDataGridView.SelectedRows[0].Index];

            foreach(DataGridViewRow uomRow in unitOfMeasureDataGridView.SelectedRows)
            {
                string sUOM = (string)uomRow.Cells["Description"].Value;
                foreach(Names desc in descriptions)
                {
                    billGuruDataSet.Product.AddProductRow(desc.codedName + CodedFieldSeperator + sUOM, desc.freeName + FreeFieldSeperator + sUOM, productTypeRow, 0f, 0f, 0f);
                }
            }
        }

        private void createProductDescriptions(ref List<Names> products, BillGuruDataSet.AttributeValueRow[][] values)
        {
            foreach (BillGuruDataSet.AttributeValueRow[] rows in values)
            {
                List<Names> newProducts;
                newProducts = new List<Names>();

                foreach (BillGuruDataSet.AttributeValueRow row in rows)
                {
                    string cv = CodedFieldSeperator + row.Acronym;
                    string fv = FreeFieldSeperator + row.AttributeValue;

                    if (products.Count > 0)
                        foreach (Names product in products)
                        {
                            newProducts.Add(new Names( product.codedName + cv, product.freeName + fv));
                        }
                    else
                        newProducts.Add(new Names(cv, fv));
                }
                if(newProducts.Count > 0)
                    products = newProducts;
            }
        }

        private void pbFill_Click(object sender, EventArgs e)
        {
            FrmInput input = new FrmInput();
            DialogResult result = input.ShowDialog();

            if (result == DialogResult.Cancel)
                return;

            string value = input.TextResult;            

            foreach (DataGridViewCell cell in productDataGridView.SelectedCells)
            {
                cell.Value = value;
            }
        }

        private void FrmStockMaster_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.billGuruDataSet.HasChanges())
                BillGuru.UI.PermissionHandler.checkDataLoss(e);
        }
    }

    struct Names
    {
        public string codedName;
        public string freeName;

        public Names(string cn, string fn) { codedName = cn; freeName = fn; }

    }
}
